package com.study.english.interceptor;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.mysql.cj.util.StringUtils;
import com.study.english.constant.SecurityConstants;
import com.study.english.context.SecurityContextHolder;
import com.study.english.exception.BusinessException;
import com.study.english.pojo.vo.SysUserVo;
import com.study.english.util.ServletUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.AsyncHandlerInterceptor;

import javax.annotation.Nullable;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;


public class HeaderInterceptor implements AsyncHandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        String authoriztion = ServletUtils.getHeader(request, SecurityConstants.AUTHORIZATION);
        if (StringUtils.isNullOrEmpty(authoriztion)) {
            throw new BusinessException("token无效");
        }
        String authorizationJson = StrUtil.replaceIgnoreCase(authoriztion, "Bearer ", "");
        String jsonStr = Base64.decodeStr(authorizationJson, "UTF-8");
        SysUserVo sysUserVo = JSON.parseObject(jsonStr, SysUserVo.class, "UTF-8");
        SecurityContextHolder.setUserId(sysUserVo.getId());
        SecurityContextHolder.setUserName(sysUserVo.getUserName());
        SecurityContextHolder.setRealName(sysUserVo.getRealName());
        return true;
    }

    @Override

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        SecurityContextHolder.remove();
    }

}
